package com.laijiale.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.laijiale.dto.*;
import com.laijiale.dto.CommentPageDTO;
import com.laijiale.entity.Comment;
import com.laijiale.entity.Course;
import com.laijiale.entity.User;
import com.laijiale.exception.ServiceException;
import com.laijiale.feign.UserFeign;
import com.laijiale.result.Result;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.laijiale.entity.Comment;
import com.laijiale.mapper.CommentMapper;
import com.laijiale.service.CommentService;
import org.apache.commons.collections4.set.UnmodifiableSet;
import org.apache.xmlbeans.impl.xb.xsdschema.Attribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import vo.CommentSimpleListVO;
import vo.CommentSimpleListVO;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

import static com.laijiale.entity.table.CommentTableDef.COMMENT;

import static com.laijiale.entity.table.SeasonTableDef.SEASON;

/**
 * 开发评论表 服务层实现。
 *
 * @author laijiale
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "comment")
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>  implements CommentService{
    @Autowired
    private UserFeign userFeign;

    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(CommentInsertDTO dto) {
        Comment comment= BeanUtil.copyProperties(dto,Comment.class);
        User user= userFeign.select(dto.getFkUserId()).getData();
        comment.setNickname(user.getNickname());
        comment.setCreated(LocalDateTime.now());
        comment.setUpdated(LocalDateTime.now());
        return mapper.insert(comment)>0;
    }

    @Cacheable(key = "#p0",condition = "#p0 !=null",unless = "#result ==null")
    @Override
    public Comment select(Long id) {
        RelationManager.addQueryRelations("episode");
        return mapper.selectOneWithRelationsById(id);
    }

    @Cacheable(key = "#root.methodName",
            unless = "#result == null"
    )
    @Override
    public List<CommentSimpleListVO> simpleList() {

        return QueryChain.of(mapper).withRelations().listAs(CommentSimpleListVO.class);
    }

    public Page<Comment> page(CommentPageDTO dto) {

        QueryChain<Comment> queryChain = QueryChain.of(mapper);

        // pid 条件
        Long pid = dto.getPid();
        if(ObjectUtil.isNotNull(pid)) {
            queryChain.where(COMMENT.PID.eq(pid));
        }
        //episodeId条件
        Long episodeId =dto.getFkEpisodeId();
        if (ObjectUtil.isNotNull(episodeId)){
            queryChain.where(COMMENT.FK_EPISODE_ID.eq(episodeId));
        }
        //userId条件
        Long userId =dto.getFkUserId();
        if (ObjectUtil.isNotNull(userId)){
            queryChain.where(COMMENT.FK_USER_ID.eq(userId));
        }
        return queryChain.withRelations().page(new Page<>(dto.getPageNum(), dto.getPageSize()));
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean update(CommentUpdateDTO dto) {

        // 组装 entity 实体类
        Comment comment = BeanUtil.copyProperties(dto, Comment.class);
        Result<User> user= userFeign.select(dto.getFkUserId());
        // 设置 entity 默认值
        comment.setUpdated(LocalDateTime.now());
        comment.setNickname(user.getData().getNickname());
        return UpdateChain.of(comment).where(COMMENT.ID.eq(comment.getId())).update();
    }
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {
        UpdateChain.of(mapper).where(COMMENT.PID.eq(id)).remove();

        return mapper.deleteById(id) > 0;

    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {
        UpdateChain.of(mapper).where(COMMENT.PID.in(ids)).remove();

        return mapper.deleteBatchByIds(ids) > 0;
    }
}
